package cn.hsa.xxx.bookData.service.impl;

import cn.hsa.xxx.bookData.bo.BookInfoBO;
import cn.hsa.xxx.api.dto.BookInfoDTO;
import cn.hsa.xxx.api.service.BookInfoService;
import cn.hsa.xxx.imgFsStore.service.ImgStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class BookInfoServiceImpl implements BookInfoService {

    @Autowired
    private BookInfoBO bookInfoBO;

    @Autowired
    private ImgStorageService imgStorageService;

    @Override
    public BookInfoDTO add(BookInfoDTO bookInfoDTO) {
        return bookInfoBO.add(bookInfoDTO);
    }

    @Override
    public BookInfoDTO get(String id) {
        return bookInfoBO.get(id);
    }

    @Override
    public List<BookInfoDTO> getPage(int pageNo, int pageSize) {
        return bookInfoBO.getPage(pageNo, pageSize);
    }

    @Override
    public void addCoverImg(MultipartFile file, String bookUuid) {
        String keyId = imgStorageService.uploadImgFile(file);
        //获取DTO
        BookInfoDTO bookInfoDTO = bookInfoBO.get(bookUuid);
        //设置bookImgAddr
        bookInfoDTO.setBookImgAddr(keyId);
        bookInfoBO.update(bookInfoDTO);
    }

    @Override
    public String getCoverImgUrl(String bookUuid) {
        String keyId = bookInfoBO.get(bookUuid).getBookImgAddr();
        String imgUrl = imgStorageService.getImgUrl(keyId);
        return imgUrl;
    }

    @Override
    public String deleteCoverImg(String bookUuid) {
        BookInfoDTO bookInfoDTO = bookInfoBO.get(bookUuid);
        //获取keyId，方便在服务器中删除源文件
        String keyId = bookInfoDTO.getBookImgAddr();
        imgStorageService.deleteImgFile(keyId);
        //将数据库中的图片id删除并更新
        bookInfoDTO.setBookImgAddr("");
        bookInfoBO.update(bookInfoDTO);
        return "删除成功";
    }


}
